import cookies from '../cookie/cookies'

import {getStateData} from './store'

import UserAPI from '../api/UserAPI'

import TeamAPI from "../api/TeamAPI";

import {delCookie} from "as-common";
import EnterpriseLevelAPI from "../api/EnterpriseLevelAPI";
import {universityActionTypes, universityTypes} from "./university";

export {userModule, userTypes, userActionsTypes}

//类型，通过commit事件类型触发事件

const userTypes = {

  SAVE_USER_INFO: 'SAVE_USER_INFO',

  EDIT_USER_INFO: 'EDIT_USER_INFO',

  SAVE_USER_MOBILE: 'SAVE_USER_MOBILE',

  EDIT_USER_BIND_CARD_ID: 'EDIT_USER_BIND_CARD_ID',

  SAVE_ENTERPRISE_USER_INFO: 'SAVE_ENTERPRISE_USER_INFO',

  SAVE_ENTERPRISE_ROLE_INFO: 'SAVE_ENTERPRISE_ROLE_INFO',

  EDIT_ENTERPRISE_USER_INFO: 'EDIT_ENTERPRISE_USER_INFO',

  SAVE_USER_MAP: 'SAVE_USER_MAP',

};


//类型，通过dispatch事件类型触发事件

const userActionsTypes = {

  FETCH_ENTERPRISE_USER_INFO: 'FETCH_ENTERPRISE_USER_INFO',

  FETCH_ENTERPRISE_ROLE_INFO: 'FETCH_ENTERPRISE_ROLE_INFO',

  FETCH_ENTERPRISE_INFO: "FETCH_ENTERPRISE_INFO",

  FETCH_USER_MAP: 'FETCH_USER_MAP',

};


const userModule = {

  state: {

    userInfo: null,

    enterpriseInfo: null,

    enterpriseRoleInfo: null,

    userMap: null,

  },


  //获取数据

  getters: {
    //Get user info from the cookie,
    userInfo: (state) => getStateData(state, 'userInfo', cookies.keys.KEY_USER_INFO, userTypes.SAVE_USER_INFO),
    userAvatar: (state, getters) => getters.userInfo.pic,
    userNickname: (state, getters) => getters.userInfo.nickname,
    enterpriseInfo: (state) => getStateData(state, 'enterpriseInfo', cookies.keys.KEY_ENTERPRISE_INFO, userTypes.SAVE_ENTERPRISE_USER_INFO),
    enterpriseRoleInfo: (state) => getStateData(state, 'enterpriseRoleInfo', cookies.keys.KEY_ENTERPRISE_ROLE_INFO, userTypes.SAVE_ENTERPRISE_ROLE_INFO),
    userMap: (state) => state.userMap || {},
  },

  //同步请求，只有这里能修改数据

  mutations: {
    //save user info
    [userTypes.SAVE_USER_INFO](state, userInfo) {
      if (!userInfo) return;
      state.userInfo = userInfo;
      cookies.saveUser(userInfo)
    },
    [userTypes.SAVE_USER_MOBILE](state, mobile) {
      if (!mobile) return;
      state.userInfo.mobile = mobile;
      cookies.saveUser(state.userInfo)
    },

    [userTypes.SAVE_ENTERPRISE_USER_INFO](state, data) {
      state.enterpriseInfo = data;
      cookies.saveEnterPrise(data);
    },

    [userTypes.SAVE_ENTERPRISE_ROLE_INFO](state, data) {
      state.enterpriseRoleInfo = data;
      cookies.saveEnterPriseRole(data);
    },
    [userTypes.SAVE_USER_MAP](state, data) {
      state.userMap = data
    },

  },

  //异步请求

  actions: {
    [userActionsTypes.FETCH_ENTERPRISE_INFO]({state, commit, dispatch}, data) {
      let enterpriseUserInfo = dispatch(userActionsTypes.FETCH_ENTERPRISE_USER_INFO);
      let EnterpriseRoleInfo = dispatch(userActionsTypes.FETCH_ENTERPRISE_ROLE_INFO);
      return Promise.all([enterpriseUserInfo, EnterpriseRoleInfo])
    },
    [userActionsTypes.FETCH_ENTERPRISE_USER_INFO]({state, commit, dispatch}, data) {
      return new Promise((resolve, reject) => {
        EnterpriseLevelAPI.getEnterpriseInfo().then((result) => {
          console.log('FETCH_ENTERPRISE_USER_INFO', result)
          commit(userTypes.SAVE_ENTERPRISE_USER_INFO, result.responseData);
          resolve(result.responseData);
        }).catch((e) => {
          reject(e);
          console.log('clearEnterPriseInfo', e)
        });
      })
    },

    [userActionsTypes.FETCH_ENTERPRISE_ROLE_INFO]({state, commit, dispatch}, data) {
      return new Promise((resolve, reject) => {
        TeamAPI.getMyTeamUser().then((result) => {
          if (result.resultCode === 0) {
            console.log('FETCH_ENTERPRISE_ROLE_INFO', result)

            commit(userTypes.SAVE_ENTERPRISE_ROLE_INFO, result.responseData);
            resolve(result.responseData)
          } else {
            reject(result)
          }
        }).catch(e => {
          reject(e);
          console.log(e)
        })

      })

    },

    [userTypes.EDIT_USER_INFO]({commit}, data) {

      return new Promise((resolve, reject) => {

        UserAPI.editUser(data).then((result) => {

          let obj = {

            data: result.responseData,

            resultCode: result.resultCode

          };

          if (result.resultCode === '000000') {

            _saveResponseUserInfo(commit, obj);

            resolve(result)

          } else {

            reject(result)

          }

        }).catch(e => {

          console.log(e)

        })

      })

    },

    [userTypes.EDIT_USER_BIND_CARD_ID]({commit}, data) {

      return new Promise((resolve, reject) => {

        UserAPI.bindIDCard(data.name, data.number).then((result) => {

          resolve(result)

        }).catch(e => {

          reject(e);

          console.log(e)

        })

      })

    },
    [userTypes.EDIT_ENTERPRISE_USER_INFO]({commit}, data) {
      return new Promise((resolve, reject) => {
        TeamAPI.modifyTeamInfo(data).then((result) => {
          let obj = {
            data: result.responseData,
            resultCode: result.resultCode
          };
          if (result.resultCode === '000000') {
            _saveResponseEnterpriseUserInfo(commit, obj);
            resolve(result)
          } else {
            reject(result)
          }
        }).catch(e => {
          console.log(e)
        })
      })
    },
    [userActionsTypes.FETCH_USER_MAP]({commit, state}, param) {
      return new Promise((resolve, reject) => {
        Promise.all([UserAPI.getUserList(param),  UserAPI.getUserExtList(param)]).then((res) => {
          let oriMap = state.userMap
          let userMap = res[0].responseData
          let userExtMap = res[1].responseData.learnValues
          for (let key in userMap) {
            userMap[key]['learnValue'] = userExtMap[key]['learnValue']
          }
          let finalMap = Object.assign({}, userMap, oriMap)
          commit(userTypes.SAVE_USER_MAP, finalMap)
          resolve(finalMap)
        }).catch((error) => {
          reject(error)
        })
      })
    },

  },

};


//在本文件公用的方法，请求结果中保存用户信息

export function _saveResponseUserInfo(commit, result) {

  if (result.resultCode === '000000') {

    let userInfo = result.data || null;

    if (userInfo) {

      commit(userTypes.SAVE_USER_INFO, userInfo)

    }

    return result

  }

}


export function _saveResponseEnterpriseUserInfo(commit, result) {

  if (result.resultCode === '000000') {

    let enterpriseInfo = result.data || null;

    if (enterpriseInfo) {

      commit(userTypes.SAVE_ENTERPRISE_USER_INFO, enterpriseInfo)

    }

    return result

  }

}


export function clearEnterPriseInfo() {

  delCookie('web-hft-ee/enterpriseInfo', true);

  delCookie('web-hft-ee/enterpriseRoleInfo', true);

}

